package com.expert.miniapp.controller;

import com.expert.miniapp.dao.ChatMessage;
import com.expert.miniapp.dao.ChatSession;
import com.expert.miniapp.dto.ChatSessionDTO;
import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.service.ChatSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * ChatController - 对话控制器
 * 提供AI对话历史记录相关接口
 *
 * @author System
 * @since 2025-10-21
 */
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private ChatSessionService chatSessionService;

    /**
     * 创建新会话
     *
     * @param requestBody 请求体，包含userId
     * @return 新创建的会话信息
     */
    @PostMapping(value = "/sessions", produces = "application/json;charset=UTF-8")
    public ResultDTO<ChatSession> createSession(@RequestBody Map<String, String> requestBody) {
        String userId = requestBody.get("userId");

        logger.info("接收到创建会话请求: userId={}", userId);

        if (userId == null || userId.trim().isEmpty()) {
            return ResultDTO.error("用户ID不能为空");
        }

        try {
            ChatSession session = chatSessionService.createSession(userId);
            logger.info("会话创建成功: sessionId={}", session.getSessionId());
            return ResultDTO.success(session);
        } catch (Exception e) {
            logger.error("创建会话失败", e);
            return ResultDTO.error("创建会话失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的所有会话列表
     *
     * @param userId 用户ID
     * @return 会话列表（按updated_at倒序）
     */
    @GetMapping(value = "/sessions", produces = "application/json;charset=UTF-8")
    public ResultDTO<List<ChatSessionDTO>> getUserSessions(@RequestParam String userId) {
        logger.info("接收到获取会话列表请求: userId={}", userId);

        if (userId == null || userId.trim().isEmpty()) {
            return ResultDTO.error("用户ID不能为空");
        }

        try {
            List<ChatSessionDTO> sessions = chatSessionService.getUserSessions(userId);
            logger.info("查询到 {} 个会话", sessions.size());
            return ResultDTO.success(sessions);
        } catch (Exception e) {
            logger.error("获取会话列表失败", e);
            return ResultDTO.error("获取会话列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取会话详情
     *
     * @param sessionId 会话ID
     * @return 会话详情
     */
    @GetMapping(value = "/sessions/{sessionId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<ChatSessionDTO> getSessionDetail(@PathVariable String sessionId) {
        logger.info("接收到获取会话详情请求: sessionId={}", sessionId);

        try {
            ChatSessionDTO session = chatSessionService.getSessionDetail(sessionId);
            if (session == null) {
                return ResultDTO.error("会话不存在");
            }
            return ResultDTO.success(session);
        } catch (Exception e) {
            logger.error("获取会话详情失败", e);
            return ResultDTO.error("获取会话详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取会话的所有消息
     *
     * @param sessionId 会话ID
     * @return 消息列表（按message_order正序）
     */
    @GetMapping(value = "/sessions/{sessionId}/messages", produces = "application/json;charset=UTF-8")
    public ResultDTO<List<ChatMessage>> getSessionMessages(@PathVariable String sessionId) {
        logger.info("接收到获取会话消息请求: sessionId={}", sessionId);

        try {
            List<ChatMessage> messages = chatSessionService.getSessionMessages(sessionId);
            logger.info("查询到 {} 条消息", messages.size());
            return ResultDTO.success(messages);
        } catch (Exception e) {
            logger.error("获取会话消息失败", e);
            return ResultDTO.error("获取会话消息失败: " + e.getMessage());
        }
    }

    /**
     * 保存一轮对话（用户消息+AI回复）
     *
     * @param sessionId 会话ID
     * @param requestBody 请求体，包含messages数组
     * @return 保存结果
     */
    @PostMapping(value = "/sessions/{sessionId}/messages", produces = "application/json;charset=UTF-8")
    public ResultDTO<Map<String, Object>> saveMessages(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> requestBody
    ) {
        logger.info("接收到保存消息请求: sessionId={}", sessionId);

        try {
            // 解析messages数组
            @SuppressWarnings("unchecked")
            List<Map<String, String>> messagesData = (List<Map<String, String>>) requestBody.get("messages");

            if (messagesData == null || messagesData.isEmpty()) {
                return ResultDTO.error("消息列表不能为空");
            }

            // 转换为ChatMessage对象
            List<ChatMessage> messages = new java.util.ArrayList<>();
            for (Map<String, String> msgData : messagesData) {
                ChatMessage msg = new ChatMessage();
                msg.setSenderType(msgData.get("senderType"));
                msg.setContent(msgData.get("content"));
                messages.add(msg);
            }

            // 保存消息
            Map<String, Object> result = chatSessionService.saveMessages(sessionId, messages);

            logger.info("保存了 {} 条消息", result.get("savedCount"));
            return ResultDTO.success(result);

        } catch (Exception e) {
            logger.error("保存消息失败", e);
            return ResultDTO.error("保存消息失败: " + e.getMessage());
        }
    }

    /**
     * 重命名会话
     *
     * @param sessionId 会话ID
     * @param requestBody 请求体，包含title
     * @return 是否成功
     */
    @PutMapping(value = "/sessions/{sessionId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<Void> renameSession(
            @PathVariable String sessionId,
            @RequestBody Map<String, String> requestBody
    ) {
        String title = requestBody.get("title");

        logger.info("接收到重命名会话请求: sessionId={}, title={}", sessionId, title);

        if (title == null || title.trim().isEmpty()) {
            return ResultDTO.error("标题不能为空");
        }

        try {
            boolean success = chatSessionService.renameSession(sessionId, title);
            if (success) {
                logger.info("会话重命名成功");
                return ResultDTO.success(null);
            } else {
                return ResultDTO.error("会话不存在");
            }
        } catch (Exception e) {
            logger.error("重命名会话失败", e);
            return ResultDTO.error("重命名会话失败: " + e.getMessage());
        }
    }

    /**
     * 删除会话
     *
     * @param sessionId 会话ID
     * @return 是否成功
     */
    @DeleteMapping(value = "/sessions/{sessionId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<Void> deleteSession(@PathVariable String sessionId) {
        logger.info("接收到删除会话请求: sessionId={}", sessionId);

        try {
            boolean success = chatSessionService.deleteSession(sessionId);
            if (success) {
                logger.info("会话删除成功");
                return ResultDTO.success(null);
            } else {
                return ResultDTO.error("会话不存在");
            }
        } catch (Exception e) {
            logger.error("删除会话失败", e);
            return ResultDTO.error("删除会话失败: " + e.getMessage());
        }
    }

    /**
     * 全局搜索会话（根据消息内容）
     *
     * @param userId 用户ID
     * @param keyword 搜索关键词
     * @return 匹配的会话列表
     */
    @GetMapping(value = "/search", produces = "application/json;charset=UTF-8")
    public ResultDTO<List<ChatSessionDTO>> searchSessions(
            @RequestParam String userId,
            @RequestParam String keyword
    ) {
        logger.info("接收到搜索请求: userId={}, keyword={}", userId, keyword);

        if (userId == null || userId.trim().isEmpty()) {
            return ResultDTO.error("用户ID不能为空");
        }

        if (keyword == null || keyword.trim().isEmpty()) {
            return ResultDTO.error("搜索关键词不能为空");
        }

        try {
            List<ChatSessionDTO> sessions = chatSessionService.searchSessions(userId, keyword);
            logger.info("搜索到 {} 个会话", sessions.size());
            return ResultDTO.success(sessions);
        } catch (Exception e) {
            logger.error("搜索会话失败", e);
            return ResultDTO.error("搜索会话失败: " + e.getMessage());
        }
    }
}
